/****************************************************************
** Product  :   HP Subscriber Network Application Policy
** Module   :   gr-manager
** Date: Apr 10, 2015               
** Author: Chen Zhen-hua
** (C) Copyright 2015, Hewlett-Packard Company, All Rights Reserved.
** This software is the proprietary information of HP, Inc.  
** Use is subject to license terms.
*****************************************************************
** Description:   
**  JSON utility class, Mainly process the Session server status from shell script return Json string.
****************************************************************/
package com.hp.snap.gr.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.snap.gr.exception.ActionException;
import com.hp.snap.gr.model.BizServiceStatus;
import com.hp.snap.gr.model.DeployRole;
import com.hp.snap.gr.model.DeployStatus;
import com.hp.snap.gr.model.GRStatus;
import com.hp.snap.gr.model.SessionServerStatus;
import com.hp.snap.gr.model.SessionServerStatus.KernelStatus;
import com.hp.snap.gr.model.SessionServerStatus.ProcessStatus;
import com.hp.snap.gr.utils.eium.JMXClientUtils;

/**
 * JSON utility class, Mainly process the Session server status from shell script return Json string.
 *
 * <P>
 * Version: 3.3 <br>
 * Author: Chen Zhen-hua
 * Date: Apr 10, 2015
 * 
 * </P>
 *
 **/
public class JSONUtils {

    private static Logger logger = LoggerFactory.getLogger(JSONUtils.class);

    public static Map<String, SessionServerStatus> getSSStatus(String resultStr, boolean remote) throws ActionException {
        Map<String, SessionServerStatus> statusMap = new HashMap<String, SessionServerStatus>();
//        String jmxURL = Utils.getJMXURL(remote);
        try {
            JSONObject json = new JSONObject(resultStr);
            JSONArray jsonArray = json.getJSONArray("results");
            for (int i = 0; i < jsonArray.length(); i++) {
//                SessionServerStatus obj = new SessionServerStatus();
                KernelStatus kernelStatus = null;
                BizServiceStatus bizServiceStatus = null;
                String ssfulName = jsonArray.getJSONObject(i).getString("session_server");
                if (logger.isDebugEnabled()) {
                    logger.debug("return the sesson server is:{}", ssfulName);
                }
				//logger.trace("The ssfulName is {}",ssfulName);
                if(ssfulName==null || ssfulName.equals("")){
                	return new HashMap<String, SessionServerStatus>();
                }
                String[] s2 = ssfulName.split("/");
                String ssType = s2[0];
                String ssHost = s2[1];
                String ssName = s2[2];
                ProcessStatus ssProcessStatus = SessionServerStatus.ProcessStatus.valueOf(jsonArray.getJSONObject(i).getString("state").toUpperCase());
                 //bizServiceStatus = BizServiceStatus.valueOf(jsonArray.getJSONObject(i).getString("biz_service_status"));
                
                if (ssProcessStatus == SessionServerStatus.ProcessStatus.RUNNING) {
                    //obj.setKernelStatus(SessionServerStatus.KernelStatus.valueOf(jsonArray.getJSONObject(i).getString("server_status").toUpperCase()));
                    kernelStatus = SessionServerStatus.KernelStatus.valueOf(jsonArray.getJSONObject(i).getString("server_status").toUpperCase());
                    try{
                        bizServiceStatus = BizServiceStatus.valueOf(jsonArray.getJSONObject(i).getString("biz_service_status"));
                    }catch(IllegalArgumentException e){
                    	bizServiceStatus = BizServiceStatus.Standby;
                    }
                }else if(ssProcessStatus == SessionServerStatus.ProcessStatus.STOPPED){
                	bizServiceStatus = BizServiceStatus.Standby;
                }
                
//                if (ssProcessStatus == ProcessStatus.STOPPED) {
//                    statusMap.put(ssfulName, new SessionServerStatus(ssfulName, ssProcessStatus, kernelStatus, BizServiceStatus.Standby));
//                } else {
//                    String ssBizStatus = (String) Utils.invokeJMXMethod(jmxURL, ssHost + "/" + ssName + "/" + Constants.JMX_SNAP_OBJECT, Constants.JMX_GET_BIZ_STATUS, null, null);
//                    statusMap.put(ssfulName, new SessionServerStatus(ssfulName, ssProcessStatus, kernelStatus, BizServiceStatus.valueOf(ssBizStatus)));
//                }
                statusMap.put(ssfulName, new SessionServerStatus(ssfulName, ssProcessStatus, kernelStatus, bizServiceStatus));

            }
        } catch (Exception e) {
            logger.error(e.toString());
            ActionException e1 = new ActionException(e.getMessage(), e);
            throw e1;
        }
        return statusMap;

    }

    /**
     * @param ssStatusMap map key is "ssType/ssHost/ssName", and the value is the SessionServerStatus object.
     * @return map key is the session server type, and the value is the session server list of this type
     */
    protected static Map<String, List<SessionServerStatus>> convertSessionServerStatusMap(Map<String, SessionServerStatus> ssStatusMap) {
        Map<String, List<SessionServerStatus>> sessionServerStatusMap = new HashMap<String, List<SessionServerStatus>>();
        Set<String> keySet = ssStatusMap.keySet();
        for (String ssful : keySet) {
            String[] s2 = ssful.split("/");
            String ssType = s2[0];
            if (sessionServerStatusMap.get(ssType) == null) {
                List<SessionServerStatus> ssSatausLst = new ArrayList<SessionServerStatus>();
                ssSatausLst.add(ssStatusMap.get(ssful));
                sessionServerStatusMap.put(ssType, ssSatausLst);
            } else {
                List<SessionServerStatus> ssSatausLst = sessionServerStatusMap.get(ssType);
                ssSatausLst.add(ssStatusMap.get(ssful));
            }
        }
        return sessionServerStatusMap;
    }

    /**
     * @param ssStatusResultJosnStr the Session server status Json String
     *                              {"results":[{"session_server":"SNAPStudio/snap460b26/SNAPStudio","state":"Running","server_status":"IDLE"},
     *                              {"session_server":"OCS/snap460b26/ocs_itestvd2","state":"Stopped"},
     *                              {"session_server":"SPRP/snap460b26/spr_itestvd2","state":"Stopped"},
     *                              {"session_server":"LB/snap460b26/lb_itestvd2","state":"Stopped"},]}
     * @return
     * @throws ActionException
     */
    public static DeployStatus getDeployStatus(String ssStatusResultJosnStr, Boolean remote, String kerConfigPath) throws ActionException {
        Map<String, SessionServerStatus> ssStatusMap = getSSStatus(ssStatusResultJosnStr, remote);
        Map<String, List<SessionServerStatus>> sessionServerStatusMap = convertSessionServerStatusMap(ssStatusMap);
        String deployName = Utils.getConfigurationValue(Constants.CFG_GRL_DEPLOY_NAME);
        if (remote)
            deployName = Utils.getCorrespondSiteName(deployName);
        DeployRole deployRole = null;
        if (Utils.checkMasterSite(deployName)) deployRole = DeployRole.MASTER;
        if (Utils.checkSlaveSite(deployName)) deployRole = DeployRole.SLAVE;
        GRStatus grStatus = GRStatusHelper.getGRStatus();
        BizServiceStatus globalBizServiceStatus = BizServiceStatus.valueOf(Utils.getConfigurationValue(kerConfigPath, Constants.CFG_RTC_BIZ_SERVICE_STATUS));
        return new DeployStatus(deployName, deployRole, grStatus, globalBizServiceStatus, sessionServerStatusMap);

    }

    public static void main(String[] args) {
        String aa = "{\"results\":[{\"session_server\":\"14:02:30,132\",\"state\":\"Stopped\"},{\"session_server\":\"|-INFO\",\"state\":\"Stopped\"},{\"session_server\":\"in\",\"state\":\"Stopped\"},{\"session_server\":\"ch.qos.logback.classic.LoggerContext[default]\",\"state\":\"Stopped\"},{\"session_server\":\"-\",\"state\":\"Stopped\"},{\"session_server\":\"Could\",\"state\":\"Stopped\"},{\"session_server\":\"NOT\",\"state\":\"Stopped\"},{\"session_server\":\"find\",\"state\":\"Stopped\"},{\"session_server\":\"resource\",\"state\":\"Stopped\"},{\"session_server\":\"[logback.groovy]\",\"state\":\"Stopped\"},]}";
        try {
            Map<String, SessionServerStatus> bb = getSSStatus(aa, true);
            System.out.println(bb);
        } catch (Exception e) {
            System.err.println(e);
        }

    }

}
